//
//  NetWorkingHandler.m
//  UI22_NSURLSession
//
//  Created by 宝龙 on 16/6/1.
//  Copyright © 2016年 宝龙. All rights reserved.
//

#import "NetworkingManager.h"
#import "SandBoxStore.h"
#import "AFNetworking.h"


@interface NetworkingManager () <NSURLSessionDelegate, NSURLSessionDataDelegate>

// 用来接收网络数据.
@property (nonatomic, strong) NSMutableData *mData;

@property (nonatomic, retain) SandBoxStore *store;

@property (nonatomic, retain) NSCache *cache;

@property (nonatomic, strong) void(^finishedBlock)(id result,NSHTTPURLResponse *response);

@property (nonatomic, strong) void(^successfulBlock)(id result);

@property (nonatomic, strong) void(^deleteBlock)(NSDictionary *deleteDic);

@property (nonatomic, strong) void(^failedBlock)(NSError *error);




@end

@implementation NetworkingManager

+ (instancetype)manager {
    static NetworkingManager *net = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        net = [[NetworkingManager alloc] init];
        net.cache = [[NSCache alloc] init];
    });
    return  net;
}


#pragma mark - 判断是否可以网络连接
- (BOOL)canConnectNetWork {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager startMonitoring];
    
    if (manager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable
        || manager.networkReachabilityStatus == AFNetworkReachabilityStatusUnknown) {
        return NO;
    }else {
        
        return YES;
    }
    
}

//判断网络状态
- (void)networkConnectStatus {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //当网络状态发生变化时会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"Wifi");
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ConnetWiFi" object:nil];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"手机网络");
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"ConnetViaWWAN" object:nil];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网");
                  [[NSNotificationCenter defaultCenter] postNotificationName:@"NONetwork" object:nil];
                break;
            case AFNetworkReachabilityStatusUnknown:
                 [[NSNotificationCenter defaultCenter] postNotificationName:@"Unknown" object:nil];
                break;
                
            default:
                break;
        }
    }];
    [manager startMonitoring];
    
    

}



#pragma mark - GET, POST 请求
//原生请求方法
- (void)getDataWithURLString:(NSString *)URLString
                  HTTPMethod:(NSString *)httpMethod
              HTTPBody:(NSDictionary *)httpBody
                    andToken:(NSString *)token forHTTPHeaderField:(NSString *)hearderField
            completion:(void (^)(id result, NSData *data, NSURLResponse *response, NSError *error))completion {
    
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:URLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0f];
    
    if ([httpMethod.uppercaseString isEqualToString:@"POST"]) {
        request.HTTPMethod = @"POST";
    }else {
        request.HTTPMethod = @"GET";
    }
    
    if(httpBody) {
        NSArray *keyArr = [httpBody allKeys];
        NSMutableString* requestBody = [[NSMutableString alloc] init];
        for (int i = 0; i < httpBody.count; i++) {
            NSString* value = [httpBody objectForKey:keyArr[i]];
            [requestBody appendFormat:@"%@=%@",keyArr[i], value];
            if (i<(keyArr.count -1)) {[requestBody appendString:@"&"];}
        }
        NSLog(@"%@",requestBody);
        request.HTTPBody = [requestBody dataUsingEncoding:NSUTF8StringEncoding];
    }
    
    
    [request setValue:token forHTTPHeaderField:hearderField];

    NSURLSessionDataTask *dataTask = nil;
    //GET请求
    if ([httpMethod.uppercaseString isEqualToString:@"GET"] || httpMethod == nil) {
        dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            id result  = nil;
            if (data) {
                result  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{

                completion(result, data, response, error);
                
            });
        }];
    }
    
    //POST 请求
    if ([httpMethod.uppercaseString isEqualToString:@"POST"]) {
        dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            id result  = nil;
            if (data) {
                 result  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            }
          
            
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result, data, response, error);
                
            });
            
        }];
    }

    [dataTask resume];
}

//AFNetWorking
- (void)AFGetDataWithUrlString:(NSString *)urlString
                  HTTPMethod:(NSString *)httpMethod
                    HTTPBody:(NSDictionary *)httpBody
                    andToken:(NSString *)token forHTTPHeaderField:(NSString *)hearderField
             successfulBlock:(void(^)(id result))successfulBlock
                 failedBlock:(void (^)(id error))failedBlock{
    
    self.successfulBlock = successfulBlock;
    self.failedBlock = failedBlock;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 5.f;
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    if (hearderField) {
          [manager.requestSerializer setValue:token forHTTPHeaderField:hearderField];
    }
  
    //GET 请求
    if ([httpMethod.uppercaseString isEqualToString:@"GET"] || httpMethod == nil) {
        [manager GET:urlString parameters:httpBody progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            self.successfulBlock(responseObject);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self failedLog:error];
            self.failedBlock(error);
        }];
        
    }
    
    //POST 请求
    if ([httpMethod.uppercaseString isEqualToString:@"POST"]) {
        [manager POST:urlString parameters:httpBody progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            self.successfulBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self failedLog:error];
            self.failedBlock(error);
        }];
    }
    
    
}

- (void)failedLog:(NSError *)error {
    NSLog(@"请求失败:%@", error);
}




@end
